//
//  API_AsyncSequence_Demo1VC.swift
//  APSwift
//
//  Created by jianbo.pei on 2024/8/15.
//

import UIKit

class API_AsyncSequence_Demo1VC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        // 使用 Task 和 for-await-in 语法来消费异步序列
        Task {
            let countdown = CountdownAsyncSequence(start: 5)
            
            for await number in countdown {
                print(number)
            }
            print("Countdown finished!")
        }
    }


}


// 定义一个异步序列
struct CountdownAsyncSequence: AsyncSequence {
    typealias Element = Int
    
    let start: Int
    
    func makeAsyncIterator() -> CountdownAsyncIterator {
        return CountdownAsyncIterator(current: start)
    }
}

struct CountdownAsyncIterator: AsyncIteratorProtocol {
    var current: Int
    
    mutating func next() async -> Int? {
        if current > 0 {
            let value = current
            current -= 1
            // 模拟异步操作的延迟
            try? await Task.sleep(nanoseconds: 1_000_000_000)
            return value
        } else {
            return nil
        }
    }
}


